package com.hyg.lib_common.loginpart;

import androidx.appcompat.app.AlertDialog;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.animation.ArgbEvaluator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.hyg.lib_base.MyView.AutoHeightViewPager;
import com.hyg.lib_base.Net.NetworkOP;
import com.hyg.lib_base.lisener.AppUpdateListener;
import com.hyg.lib_base.lisener.PermissionListener;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.R;
import com.hyg.lib_common.ThirdSDK.PuGongYing;
import com.hyg.lib_common.WebView.WebViewActivity;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.sweetalertdialog.MyDialog;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.tencent.sonic.sdk.SonicSession;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;

@Route(path = Constants.PATH_ACTIVITY_MODULE_USER_LOGIN)
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    protected void onStop() {
        super.onStop();
        if (this.isFinishing()) {
            myHandler.removeCallbacksAndMessages(null);
        }
    }

    TextView tv_text1; // 标签栏中的页面1标签
    TextView tv_text2; // 标签栏中的页面2标签
    TextView tv_line1, tv_line2; // 标签栏中的页面3标签
    View view1;// 在页面1里的所有视图控件的调用需要使用的前缀
    View view2;// 在页面2里的所有视图控件的调用需要使用的前缀
    private List<TextView> textList; // 文字集合
    AutoHeightViewPager mViewPager;
    private Button bt_register1, bt_register2;
    //    private ImageView back;
    private Button login_phone, login_pass;
    private EditText et_code, et_phone, et_pass, et_name;
    private Button getcode, forget;
    private ToggleButton togglePwd;
    private String code = "";
    private String phone = "";
    private String password = "";
    public String mphone = "[1][345789]\\d{9}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mcode = "\\d{4,6}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mpassword = "[A-Za-z0-9]{6,18}";//第一位是字母，后面加上4-15个

    private Timer mTimer = null;
    private int PrivacyBuilding = -1;
    //    private View privacyview;
    //    private WebView privacyWebview;
    private SonicSession sonicSession;

    private CheckBox CB_Agreement;
    private TextView Agreement;


    ProgressBar progressBar;

    private MyHandler myHandler = new MyHandler(this);

    private class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private LoginActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (LoginActivity) reference.get();
        }

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://用手机号和密码登录
                    try {
                        //{"code":200,"message":"操作成功","data":{"code":500,"message":null,"data":{"message":"该手机号没有注册","status":1}}}
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
                        //                        Log.d("welcomeadLogin", jsondata + "");
                        if (status.equals("200")) {
                            JSONObject data = new JSONObject(jsondata.getString("data"));
                            if (data.getString("code").equals("200")) {
                                JSONObject datas = new JSONObject(data.getString("data"));
                                //                                loginLoading(1);
                                if (activity.pDialog.isShowing())
                                    activity.pDialog.dismiss();
                                Log.d("LoginUser", datas.getString("token"));
                                activity.editorn = activity.sn.edit();
                                activity.editorn.putString("phone", activity.phone);
                                activity.editorn.putString("password", activity.password);
                                activity.editorn.putString("token", datas.getString("token"));
                                activity.editorn.commit();
                                activity.myHandler.sendEmptyMessage(101);
                            } else {
                                String messages = new JSONObject(data.getString("data")).getString("message");
                                String ErrorStatus = new JSONObject(data.getString("data")).getString("status");
                                if (ErrorStatus.equals("1")) {
                                    if (activity.pDialog.isShowing())
                                        activity.pDialog.dismiss();
                                    activity.pDialog = new SweetAlertDialog(activity, SweetAlertDialog.ERROR_TYPE);
                                    activity.pDialog.setTitleText(messages);
                                    activity.pDialog.setCancelable(false);
                                    activity.pDialog.setConfirmButton("去注册", new SweetAlertDialog.OnSweetClickListener() {
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                            Intent it = new Intent(activity, RegisterActivity.class);
                                            it.putExtra("phone", activity.phone);
                                            it.putExtra("code", activity.code);
                                            activity.startActivity(it);
                                            activity.overridePendingTransition(R.anim.fade, R.anim.hold);
                                        }
                                    });
                                    activity.pDialog.show();
                                } else {
                                    if (activity.pDialog.isShowing())
                                        activity.pDialog.dismiss();
                                    activity.ErrorDialog(messages);
                                }
                            }
                        } else {
                            if (activity.pDialog.isShowing())
                                activity.pDialog.dismiss();
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    }
                    break;
                case 2://获取注册验证码
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String success = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
                        //                        Log.d("welcomeadLogin", jsondata + "");
                        if (success.equals("200")) {
                            if (!message.equals("")) {
                                Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            if (activity.pDialog.isShowing())
                                activity.pDialog.dismiss();
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    }
                    break;
                case 3://用手机号和验证码登录
                    try {

                        //{"code":200,"message":"操作成功","data":{"code":500,"message":null,"data":{"message":"该手机号没有注册","status":1}}}
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");

                        //                        Log.d("welcomeadLogin", jsondata + "");
                        if (status.equals("200")) {
                            if (!Utils.isEmpty(jsondata.getString("data")) && !jsondata.getString("data").equals("null")) {
                                JSONObject data = new JSONObject(jsondata.getString("data"));
                                if (activity.pDialog.isShowing())
                                    activity.pDialog.dismiss();

                                activity.editorn = activity.sn.edit();
                                activity.editorn.putString("phone", activity.phone);
                                activity.editorn.putString("password", activity.password);
                                activity.editorn.putString("token", data.getString("token"));
                                activity.editorn.commit();
                                activity.myHandler.sendEmptyMessage(101);

                            } else {
                                String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
                                //                                loginLoading(2);
                                activity.ErrorDialog(message);
                            }
                        } else {
                            JSONObject data = new JSONObject(jsondata.getString("data"));
                            String messages = data.getString("message");
                            String ErrorStatus = data.getString("status");
                            if (ErrorStatus.equals("1")) {
                                if (activity.pDialog.isShowing())
                                    activity.pDialog.dismiss();
                                activity.pDialog = new SweetAlertDialog(activity, SweetAlertDialog.ERROR_TYPE);
                                activity.pDialog.setTitleText(messages);
                                activity.pDialog.setCancelable(false);
                                activity.pDialog.setConfirmButton("去注册", new SweetAlertDialog.OnSweetClickListener() {
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                        Intent it = new Intent(activity, RegisterActivity.class);
                                        it.putExtra("phone", activity.phone);
                                        it.putExtra("code", activity.code);
                                        activity.startActivity(it);
                                        activity.overridePendingTransition(R.anim.fade, R.anim.hold);
                                    }
                                });
                                activity.pDialog.show();
                            } else {
                                activity.ErrorDialog(messages);
                            }
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    }
                    break;
                case 4:
                    ReceiveData receiveData = com.alibaba.fastjson.JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
                    PrivacyBuilding = 1;
                    if (receiveData.getCode().equals("200")) {
                        if (!Utils.isEmpty(receiveData.getData())) {
                            com.alibaba.fastjson.JSONObject data = JSON.parseObject(receiveData.getData());
                            PrivacyBuilding = Integer.parseInt(data.getString("systemVersion"));
                        }
                        check_privacy_web(PrivacyBuilding);
                    }
                    break;
                case 100://倒计时的Dialog
                    activity.getcode.setText(activity.countdown + "s后可获取");
                    activity.getcode.setAlpha(0.5f);
                    if (0 == activity.countdown) {
                        //停止倒计时显示页面
                        activity.resume();
                        activity.stopTimer();
                        return;
                    }
                    activity.countdown--;
                    break;
                case 101://登录提示的 dialog 消失
                    if (activity.pDialog.isShowing())
                        activity.pDialog.dismiss();
//                    Intent intent = new Intent(LoginActivity.this, MainView.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    // 如果要被开启的activity已经在当前的task中运行，系统不会生成该activity的一个新的实例，在该栈顶部的所有其他的activity会被销毁，这个intent通过 onNewIntent()被传递给该重新运行的activity的实例（现在在栈顶部）。
//                    startActivity(intent);// 跳转
//                    finish();
                    activity.ToIntent(Constants.PATH_ACTIVITY_MAIN, true);
                    activity.overridePendingTransition(R.anim.fade, R.anim.hold);
                    break;
            }
        }
    }

    ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        setSetDefaultStatus5(R.color.transparent);
        super.onCreate(savedInstanceState);
        Log.d(TAG, "Login.onCreate()");
        setContentView(R.layout.activity_login);
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 00, null, null, true);
        init();
    }

    public void init() {
        tv_text1 = (TextView) findViewById(R.id.text1);
        tv_text2 = (TextView) findViewById(R.id.text2);
        tv_line1 = (TextView) findViewById(R.id.line1);
        tv_line2 = (TextView) findViewById(R.id.line2);
        mViewPager = (AutoHeightViewPager) findViewById(R.id.viewFlipper1);// 定义页面设置成带有动画和滑动效果的mViewpager对象
        List<View> mList = new ArrayList<View>(); // 创建一个List，用于存放4个页面
        textList = new ArrayList<TextView>();
        textList.add(tv_text1);
        textList.add(tv_text2);

        LayoutInflater inflater = LayoutInflater.from(this);// 调用LayoutInflater类
        view1 = inflater.inflate(R.layout.login_phone, null);
        view2 = inflater.inflate(R.layout.login_pass, null); // 定义view2对象，与R.layout.view2页面关联
        mList.add(view2);
        mList.add(view1);
        MyPagerAdapter adapter = new MyPagerAdapter(mList);
        mViewPager.setAdapter(adapter); // 将adapter设置为mViewPager的adapter
        mViewPager.setOnPageChangeListener(adapter); // 使mViewPager响应OnChangeListener事件
        tv_text1.setOnClickListener(this); // 设置页面1标签的点击事件
        tv_text2.setOnClickListener(this); // 设置页面2标签的点击事件

        //        back = (ImageView) findViewById(R.id.back);
        //        back.setOnClickListener(new View.OnClickListener() {
        //            public void onClick(View v) {
        //                if (Utils.isFastClick()) {
        //                    return;
        //                }
        //                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        //            }
        //        });

        bt_register1 = (Button) view1.findViewById(R.id.bt_register);
        bt_register2 = (Button) view2.findViewById(R.id.bt_register);
        bt_register1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                IntentRegister();
            }
        });
        bt_register2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                IntentRegister();
            }
        });
        CB_Agreement = (CheckBox) findViewById(R.id.CB_Agreement);
        CB_Agreement.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setIsCheckAgreement();
            }
        });
        Agreement = (TextView) findViewById(R.id.Agreement);
        Agreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        Agreement.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
//                show_privacy_dialog(PrivacyBuilding);
                Intent it = new Intent(LoginActivity.this, WebViewActivity.class);
                it.putExtra("url", UrlUtils.PrivacyUrl);
                it.putExtra("title","隐私政策与免责声明");
                it.putExtra("type","Privacy");
                startActivity(it);
            }
        });

        initPhone();
        initPass();

        getPermissions(needPermissions, new PermissionListener() {
            @Override
            public void onResult(int[] results) {
                if (results[0] != 0) {
                    Toast.makeText(LoginActivity.this, "此应用需要用户授予读写权限", Toast.LENGTH_LONG).show();
                    getPermissions(needPermissions, new PermissionListener() {
                        @Override
                        public void onResult(int[] results) {
                            if (results[0] != 0) {
                                check_privacy_policy_building();
                            } else {
                                check_version_update(false, false);
                            }
                        }
                    });
                } else {
                    check_version_update(false, false);
                }
            }
        });
    }


    public void check_version_update(final boolean IsShowText, boolean isSystemSetting) {
        new PuGongYing().getUpdateVersion(this, IsShowText, isSystemSetting, new AppUpdateListener() {
            @Override
            public void onStart() {
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                updateDialog = builder.create();
                updateDialog = new MyDialog(LoginActivity.this, com.hyg.lib_common.R.style.alert_dialog_light);
                View dialogView = View.inflate(LoginActivity.this, com.hyg.lib_common.R.layout.dialog_update_version, null);
                TextView TvContent = dialogView.findViewById(com.hyg.lib_common.R.id.content_tv);
                TvContent.setText("应用更新中,请稍候...");
                progressBar = dialogView.findViewById(com.hyg.lib_common.R.id.progress_bar);
                updateDialog.setView(dialogView);
                updateDialog.setCancelable(false);
                updateDialog.show();
            }

            @Override
            public void onProgress(int progress) {
                if (progressBar != null) {
                    progressBar.setProgress(progress);
                }
            }

            @Override
            public void onFail() {
                if (updateDialog != null && updateDialog.isShowing()) {
                    updateDialog.dismiss();
                }

            }

            @Override
            public void onSuccess() {
                if (updateDialog != null && updateDialog.isShowing()) {
                    updateDialog.dismiss();
                }
            }

            @Override
            public void onCancel() {
                if (updateDialog != null && updateDialog.isShowing()) {
                    updateDialog.dismiss();
                }
                check_privacy_policy_building();
            }

            @Override
            public void onNoUpdateVersion() {
                check_privacy_policy_building();
            }
        });
    }

    public void check_privacy_web(int PrivacyBuilding){
        if(!Utils.isEmpty(ssu.getInt("PrivacyBuild",-1))) {
            int privacyVersion=ssu.getInt("PrivacyBuild", -1);
            if ( privacyVersion < PrivacyBuilding) {
                show_privacy_dialog(PrivacyBuilding);
            }
        }
    }

    public void show_privacy_dialog(int privacyVersion){
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_privacy, null);
        final TextView JumpPrivacyText  = view.findViewById(R.id.PrivacyName);
        JumpPrivacyText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Utils.isFastClick())return;
                Intent it = new Intent(LoginActivity.this, WebViewActivity.class);
                it.putExtra("url", UrlUtils.PrivacyUrl);
                it.putExtra("title","隐私政策与免责声明");
                it.putExtra("type","Privacy");
                startActivity(it);
            }
        });
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE);
        pDialog.setTitleText("隐私政策与免责声明");
        pDialog.setCustomView(view);
        pDialog.setConfirmButton("我同意", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                editorn = ssu.edit();
                editorn.putInt("PrivacyBuild",privacyVersion);
                editorn.apply();
                CB_Agreement.setChecked(true);
                sweetAlertDialog.dismiss();
            }
        });
        pDialog.setCancelButton("暂不使用", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                finishAffinity();
            }

        });
        pDialog.setCancelable(false);
        pDialog.show();
    }


    public void IntentRegister() {
        if (Utils.isFastClick()) {
            return;
        }
        Intent its = new Intent(LoginActivity.this, RegisterActivity.class);
        startActivity(its);
        //        finish();
        overridePendingTransition(R.anim.fade, R.anim.hold);
        //        show_privacy();
    }

    public void initPhone() {
        login_phone = (Button) view1.findViewById(R.id.login);
        getcode = (Button) view1.findViewById(R.id.getcode);
        et_code = (EditText) view1.findViewById(R.id.et_code);
        et_phone = (EditText) view1.findViewById(R.id.userphone);
        login_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                phone = et_phone.getText().toString();
                code = et_code.getText().toString();
                AutoLoginPhone(phone, code);
            }
        });

        getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = et_phone.getText().toString();
                if (Utils.isFastClick()) {
                    return;
                }
                if (phone.equals("")) {
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
                    pDialog.setTitleText("格式错误");
                    pDialog.setContentText("电话号码不可为空，请填写电话号码");
                    pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    pDialog.show();
                } else if (!phone.matches(mphone)) {
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
                    pDialog.setTitleText("格式错误");
                    pDialog.setContentText("电话号码格式不对，请重新输入。");
                    pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    pDialog.show();
                    et_phone.setText("");
                } else {
                    et_code.setHint("请注意查看短信");
                    startTimer();
                    String str_tag = "2";
                    FormBody formBody = new FormBody.Builder()
                            .add("phone", phone)//设置参数名称和参数值
                            .build();
                    sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.codeaddr);
                }
            }
        });
    }

    /* 登录提示对话框 */
    public void loginLoading(int numType) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        if (numType == 0) {
            View view = View.inflate(this, R.layout.dialog_loading, null);
            TextView loadingText = (TextView) view.findViewById(R.id.loadingText);
            //            SpinKitView spin_kit = (SpinKitView)view.findViewById(R.id.spin_kit);
            loadingText.setText("正在登录中...");
            pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.NORMAL_TYPE);
            pDialog.setCustomView(view);
            pDialog.setConfirmButton("好的", new SweetAlertDialog.OnSweetClickListener() {
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                }
            });
        } else if (numType == 1) {
            pDialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE);
            pDialog.setTitleText("登录成功");
        } else {
            pDialog = new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE);
            pDialog.setTitleText("登录失败");
        }
        pDialog.show();
    }


    public void initPass() {
        login_pass = (Button) view2.findViewById(R.id.login);
        et_pass = (EditText) view2.findViewById(R.id.password);
        forget = (Button) view2.findViewById(R.id.forget);
        et_name = (EditText) view2.findViewById(R.id.userphone);
        togglePwd = (ToggleButton) view2.findViewById(R.id.togglePwd);
        togglePwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) { //如果选中，显示密码
                    et_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else { //否则隐藏密码
                    et_pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        login_pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                phone = et_name.getText().toString();
                password = et_pass.getText().toString();
                //                if (UINetWork(NetworkUtils.isConnected(Login.this)))//检查网络是否断开的 提示，决定是否访问服务器
                AutoLoginPassword(phone, password);
            }
        });
        forget.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                Intent it = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                startActivity(it);
                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
    }

    protected void onResume() {
        super.onResume();
        Log.d(TAG, "Login.onResume()");
        if (!Utils.isEmpty(sn.getString("phone", ""))) {
            phone = sn.getString("phone", "");
            et_phone.setText(phone);
            et_name.setText(phone);
        }

    }

    public void AutoLoginPhone(String phone, String code) {
        //        Log.d("wel", phone + "|" + code);

        if (phone.equals("")) {
            if (pDialog.isShowing())
                pDialog.dismiss();
            pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
            pDialog.setTitleText("格式错误");
            pDialog.setContentText("请填写手机号");
            pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                }
            });
            pDialog.show();
        } else if (code.equals("")) {
            if (pDialog.isShowing())
                pDialog.dismiss();
            pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
            pDialog.setTitleText("格式错误");
            pDialog.setContentText("请填写验证码");
            pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                }
            });
            pDialog.show();
        } else {
            if (!phone.matches(mphone)) {
                if (pDialog.isShowing())
                    pDialog.dismiss();
                pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
                pDialog.setTitleText("格式错误");
                pDialog.setContentText("手机号格式错误，请重新输入");
                pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                });
                pDialog.show();
            } else if (!code.matches(mcode)) {
                if (pDialog.isShowing())
                    pDialog.dismiss();
                pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
                pDialog.setTitleText("格式错误");
                pDialog.setContentText("验证码格式错误，请重新输入");
                pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                });
                pDialog.show();
            } else {
                loginLoading(0);
                String str_tag = "3";
                FormBody formBody = new FormBody.Builder()
                        .add("phone", phone)//设置参数名称和参数值
                        .add("smsCode", code)//设置参数名称和参数值
                        .build();
                sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.loginPhoneAddr);
            }
        }
    }

    public void AutoLoginPassword(String username, String password) {
        if (username.equals("")) {
            if (pDialog.isShowing())
                pDialog.dismiss();
            pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
            pDialog.setTitleText("格式错误");
            pDialog.setContentText("请填写手机号");
            pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                }
            });
            pDialog.show();
        } else if (password.equals("")) {
            if (pDialog.isShowing())
                pDialog.dismiss();
            pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
            pDialog.setTitleText("格式错误");
            pDialog.setContentText("密码不可为空，请填写密码。");
            pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                }
            });
            pDialog.show();
        } else {
            if (!username.matches(mphone)) {
                if (pDialog.isShowing())
                    pDialog.dismiss();
                pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
                pDialog.setTitleText("格式错误");
                pDialog.setContentText("手机号格式错误，请重新输入");
                pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                });
                pDialog.show();
                et_name.setText("");
            } else if (!password.matches(mpassword)) {
                if (pDialog.isShowing())
                    pDialog.dismiss();
                pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE);
                pDialog.setTitleText("格式错误");
                pDialog.setContentText("密码格式不对或者包含非格式字符，请重新输入");
                pDialog.setConfirmButton("好，知道啦", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                });
                pDialog.show();
                et_pass.setText("");
            } else {
                loginLoading(0);
                String str_tag = "1";
                FormBody formBody = new FormBody.Builder()
                        .add("phone", username)//设置参数名称和参数值
                        .add("password", password)//设置参数名称和参数值
                        .build();
                sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.loginPwdAddr);
            }
        }
    }

    /*  滑动切换页面的控件 */
    class MyPagerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener {
        // PagerAdapter主要是viewpager的适配器，而viewPager则也是在android.support.v4扩展包中新添加的一个强大的控件，可以实现控件的滑动效果，比如咱们在软件中常见的广告栏的滑动效果，用viewPager就可以实现
        private List<View> mList;

        // 构造函数，接收List参数，以便对其中的元素（页面）进行操作
        public MyPagerAdapter(List<View> views) {
            mList = views;
        }

        // 返回页面的数量
        @Override
        public int getCount() {// 获取要滑动的控件的数量
            return mList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {// 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) { // PagerAdapter只缓存三张要显示的图片，如果滑动的图片超出了缓存的范围，就会调用这个方法，将图片销毁
            container.removeView(mList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {// 当要显示的图片可以进行缓存的时候，会调用这个方法进行显示图片的初始化，我们将要显示的ImageView加入到ViewGroup中，然后作为返回值返回即可
            container.addView(mList.get(position), 0);
            return mList.get(position);
        }

        // 此方法和下面的onPageScrolled方法是实现OnPageChangeListener接口必须覆盖的方法
        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            ArgbEvaluator evaluator = new ArgbEvaluator(); // ARGB求值器
            //            int evaluate = 0x00FFFFFF; // 初始默认颜色（透明白）
            //            int evaluate2 = 0X00FFFFFF;
            //            int evaluate3 = 0X00FFFFFF;
            //            int evaluate4 = 0X00FFFFFF;
            if (position == 0) {
                //                evaluate = (Integer) evaluator.evaluate(positionOffset, 0XFF7b40be, 0X88000000); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                //                evaluate2 = (Integer) evaluator.evaluate(positionOffset, 0X88000000, 0XFF7b40be); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                //                evaluate3 = (Integer) evaluator.evaluate(positionOffset, 0XFFD0C1EB, 0X00FFFFFF); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                //                evaluate4 = (Integer) evaluator.evaluate(positionOffset, 0X00FFFFFF, 0XFFD0C1EB); // 根据positionOffset和第0页~第1页的颜色转换范围取颜色值
                tv_text1.setTextColor((Integer) evaluator.evaluate(positionOffset, 0XFF7b40be, 0X88000000));
                tv_line1.setBackgroundColor((Integer) evaluator.evaluate(positionOffset, 0XFFD0C1EB, 0X00FFFFFF));

                tv_text2.setTextColor((Integer) evaluator.evaluate(positionOffset, 0X88000000, 0XFF7b40be));
                tv_line2.setBackgroundColor((Integer) evaluator.evaluate(positionOffset, 0X00FFFFFF, 0XFFD0C1EB));
                //                Log.d("offset", positionOffset + "\n");
            } else if (position == 1) {

            } else if (position == 2) {
            } else {
                //                evaluate = 0XFF00AB96; // 最终第3页的颜色
            }
            //				((View)mViewPager.getParent()).setBackgroundColor(evaluate); // 为ViewPager的父容器设置背景色 }
        }

        // 当page被选择的时候，将此页标签上的文字设置为白色，其他标签上的文字设置为黑色，position从0开始
        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:// 将页面1设置成白色
                    tv_text1.setTextColor(getResources().getColor(R.color.MainThemeColor));
                    tv_text2.setTextColor(getResources().getColor(R.color.black));
                    tv_line1.setBackgroundColor(getResources().getColor(R.color.gradient_Violet));
                    tv_line2.setBackground(null);

                    break;
                case 1:// 将页面2设置成白色
                    tv_text1.setTextColor(getResources().getColor(R.color.black));
                    tv_text2.setTextColor(getResources().getColor(R.color.MainThemeColor));
                    tv_line1.setBackground(null);
                    tv_line2.setBackgroundColor(getResources().getColor(R.color.gradient_Violet));
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        int index = 0;
        int id = v.getId();
        if (id == R.id.text1) {
            index = 0;
        } else if (id == R.id.text2) {
            index = 1;
        }
        mViewPager.setCurrentItem(index); // 设置当前显示的页面
    }

    //开始倒计时
    private void startTimer() {
        //点击获取验证码后改变按钮的状态,让按钮不可点击
        getcode.setClickable(false);
        if (mTimer == null) {
            mTimer = new Timer(true);
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                myHandler.sendEmptyMessage(100);
            }
        }, 0, 1000);
    }

    private int countdown = 60;

    private void resume() {
        stopTimer();
        countdown = 45;
        //倒计时结束后,让按钮重新可点击
        getcode.setClickable(true);
        getcode.setText("获取验证码");
        getcode.setAlpha(0.9f);
    }


    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public void check_privacy_policy_building() {
        /* 查询隐私政策版本号*/
        String str_tag = "4";
        FormBody formBody = new FormBody.Builder()
                .build();
        NetworkOP op = new NetworkOP(str_tag, formBody, myHandler, UrlUtils.PrivacyAddr);
        //使用类的对象op将三个实参发送，通过handler传递参数到NetworkOP中去，在NetworkOP将数据包装发送到规定的互联网地址
        op.okhttpAsyncGet();
    }


    public void setIsCheckAgreement() {
        /*检测条款是否选上*/
        if (CB_Agreement.isChecked()) {
            CB_Agreement.setChecked(true);
        } else {
//            CB_Agreement.setChecked(false);
            show_privacy_dialog(PrivacyBuilding);
        }
    }

    @SuppressLint("NewApi")
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.REQUEST_INSTALL_PACKAGES,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
    };
    private static final int PERMISSON_REQUESTCODE = 0;
    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //如果是返回键
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //重写返回键 改为同home键相同功能
            Intent intent = new Intent(Intent.ACTION_MAIN);
            //            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }

}
